package com.taskmanagement.service;

import com.taskmanagement.dto.AuthResponse;
import com.taskmanagement.dto.LoginRequest;
import com.taskmanagement.dto.RegisterRequest;
import com.taskmanagement.entity.User;
import com.taskmanagement.security.JwtTokenProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

@Service
public class AuthService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserService userService;

    @Autowired
    private JwtTokenProvider tokenProvider;

    public AuthResponse register(RegisterRequest registerRequest) {
        User user = userService.createUser(
                registerRequest.getUsername(),
                registerRequest.getEmail(),
                registerRequest.getPassword(),
                registerRequest.getFullName()
        );

        String jwt = tokenProvider.generateTokenFromUsername(user.getUsername());

        return new AuthResponse(jwt, user.getUsername(), user.getEmail());
    }

    public AuthResponse login(LoginRequest loginRequest) {
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(
                        loginRequest.getUsername(),
                        loginRequest.getPassword()
                )
        );

        SecurityContextHolder.getContext().setAuthentication(authentication);
        String jwt = tokenProvider.generateToken(authentication);

        User user = userService.findByUsername(loginRequest.getUsername());
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        return new AuthResponse(jwt, user.getUsername(), user.getEmail());
    }

    public void logout(String token) {
        if (token != null) {
            // 使当前的 JWT 失效
            // 方法1: 将 token 加入黑名单（需要存储机制，如 Redis）
            // tokenBlacklistService.addToBlacklist(token, tokenProvider.getExpirationFromToken(token));

            // 方法2: 清除当前的安全上下文
            SecurityContextHolder.clearContext();

            // 注意：由于 JWT 本身是无状态的，一旦签发就无法真正"撤销"
            // 常见做法是维护一个黑名单或者使用较短的过期时间
        }
    }

}
